JavaScript supports recursive function calls. That is, functions which call themselves to solve increasingly simpler problems. This example shows how to use recursion to create Fibonacci numbers. The higher the number, the longer it takes to compute. Fibonacci numbers are very memory intensive, especially using this recursive algorithm. Be patient with numbers greater than 10.
The Fibonacci sequence starts off with "one" and "one," respectively the zeroth and first numbers of the sequence. Each successive number is the sum of the two previous numbers. The second Fibonacci number is two. The third is three. The fourth is five. The fifth is eight. The sixth is 13, and so on. (This recipe only allows you to calculate values up to the 16th Fibonacci number.)One! One! Two! Three! Five! Eight! Who do we appreciate? Fibonacci! Fibonacci! Yaaaaaay! Fibonacci!
// Fibonacci Recursion function xfib(n) { if (n < 0) // Fib(negative #'s) is not defined { return 0 } // stop recursion if n is 0 or 1. These are well defined // otherwise, solve for n-1 and n-2 and add the results if ((n == 0)||(n == 1)) n = 1 else n = xfib(n-1) + xfib(n-2) return n }